package dnl.jexem.cmd;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.SystemUtils;

public class LocalExecutionAsScript extends LocalCommandExcecution {

	private final String scriptContents;
	private LocalCommandExcecution delegate;

	public LocalExecutionAsScript(String scriptContents) {
		super("dummy");
		this.scriptContents = scriptContents;
	}

	@Override
	public void executeCommand(long timeout, boolean block) {
		String scriptsName = "tmpScript";
		if(SystemUtils.IS_OS_WINDOWS){
			scriptsName += ".bat";
		}
		File tmpScript = new File(scriptsName);
		String contents = scriptContents;
		if(SystemUtils.IS_OS_UNIX){
			contents = scriptContents.startsWith("#!/bin/bash") ? scriptContents
					: "#!/bin/bash\n" + scriptContents;
		}
		try {
			FileUtils.writeStringToFile(tmpScript, contents);
			tmpScript.setExecutable(true);
			delegate = new LocalCommandExcecution(tmpScript.getAbsolutePath());
			delegate.executeCommand(timeout, block);
		} catch (IOException e) {
			exceptionMessages.add(e.getMessage());
            setExecutionStatus(ExecutionStatus.TERMINATED);
			this.terminationReason = TerminationReason.CANNOT_CREATE_LOCAL_SCRIPT;
		} finally {
			try {
				FileUtils.forceDelete(tmpScript);
			} catch (IOException e) {
				exceptionMessages.add("LocalExcecutionAsScript: Cannot remove tmp script.");
			}
		}
	}

	@Override
	public String getErrorOutput() {
		return delegate.getErrorOutput();
	}

	@Override
	public String[] getExceptionMessages() {
		return delegate.getExceptionMessages();
	}

	@Override
	public ExecutionStatus getExecutionStatus() {
		if (this.getExecutionStatus() != null) {
			return getExecutionStatus();
		}
		return delegate.getExecutionStatus();
	}

	@Override
	public int getExitStatus() {
		return delegate.getExitStatus();
	}

	@Override
	public String getOutput() {
		return delegate.getOutput();
	}

	@Override
	public boolean hasCompleted() {
		return delegate.hasCompleted();
	}

	@Override
	public boolean hasExited() {
		return delegate.hasExited();
	}

	@Override
	public void kill() {
		delegate.kill();
	}

}
